package org.khd.auth.interceptor;

import org.khd.auth.context.LoginContext;
import org.khd.auth.mapper.RolePermissionMapper;
import org.khd.base.annotation.BasePermission;
import org.khd.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /*
    * 返回类型 boolean
    *           false 拦截 请求不会到达Controller里的方法
    *           true  放行
    *           1.获取请求头 Token
    *           2.后台验证   Token
    * */


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        //1.获取请求头 Token
        String token = request.getHeader("Token");
        //后台验证   Token
        //2.Token 为空
        if (token == null){//用户未登录
            //返回一个特定的JSON，前端根据特定的JSON，跳转到登录页面
            //格式转换 {"success":false,"msg":"请先登录"}
            PrintWriter responseWriter = response.getWriter();
            responseWriter.print("{\"success\":false,\"msg\":\"请先登录\"}");
            return false;
        }
        //3.Token 过期
        Employee employee = LoginContext.context.get(token);
        if (employee == null){
            //前端携带了Token，但后台的map找不到数据，说明用户Token过期
            PrintWriter responseWriter = response.getWriter();
            responseWriter.print("{\"success\":false,\"msg\":\"请先登录\"}");
            return false;
        }
        //4.验证当前的用户访问的功能权限，有权限的功能放行；反之，拦截
        //4.1当前访问的功能是否要做权限检查
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //4.2获取用户调用的真实的Method
        Method method = handlerMethod.getMethod();
        //4.3获取method上的权限注解
        BasePermission annotation = method.getAnnotation(BasePermission.class);
        if (annotation != null){//用户访问的方法需要做权限检查
            //5.当前的登录用户是否有访问当前资源的权限
            //5.1当前用户拥有的资源权限
            List<String> permissionSnByEmpId = rolePermissionMapper.getPermissionSnByEmpId(employee.getId());
            //5.2获取当前用户访问资源的sn
            String methodName = method.getName();
            Class<?> beanType = handlerMethod.getBeanType();
            String className = beanType.getSimpleName();
            if (permissionSnByEmpId.contains(className + ":" + methodName)){
                return true;
            }else {
                //当前的用户没有权限来访问资源
                PrintWriter responseWriter = response.getWriter();
                responseWriter.print("{\"success\":false,\"msg\":\"权限不足\"}");
                return false;
            }
        }
        return true;
    }
}
